var express = require('express');
var router = express.Router();
const upload = require('multer')();
const controller2 = require('./tass2.controller');

function makeResponse(code, message, data) {
    return {
        status: code,
        message,
        data
    };
}

router.post('/query_vpn_stat', async(req, res, next) => {
    let data = await controller2.queryVpnStat(req, res);

    return res.send(makeResponse(0, "", data));
});

router.post('/query_cert_list', async(req, res, next) => {
    let data = await controller2.queryCertList(req, res);
    return res.send(makeResponse(0, "", data));
});

router.post('/edit_cert', async(req, res, next) => {
    let data = await controller2.editCert(req, res);
    if(data && data.length >0) {
        return res.send(makeResponse(0, "", data));
    } else {
        return res.send(makeResponse(-1, "生成签名请求文件失败", data));
    }
});

router.post('/import_certs', upload.any(), async(req, res, next) => {
    if (!req.files || req.files.length < 3) {
        let result = {
            status: -1,
            data: "",
            message:"文件导入不全"
          }
        return res.send(result);
    }

    let data = await controller2.importCerts(req, res);
    if(data == 0) {
        return res.send(makeResponse(0, "", data));
    } else {
        return res.send(makeResponse(-1, "导入秘钥失败", data));
    }
});

router.post('/query_vpn_conf', async(req, res, next) => {
    let data = await controller2.queryVpnConfs(req, res);
    return res.send(makeResponse(0, "", data));
});

router.post('/add_new_vpn', async(req, res, next) => {
    let ret = await controller2.addVpnConf(req, res);
    return res.send(makeResponse(0, "", ret));
});

router.post('/edit_vpn', async(req, res, next) => {
    let ret = await controller2.editVpnConf(req, res);
    return res.send(makeResponse(0, "", ret));
});

router.post('/del_vpn', async(req, res, next) => {
    let ret = await controller2.delVpnConf(req, res);
    return res.send(makeResponse(0, "", ret));
});

router.post('/open_vpn', async(req, res, next) => {
    let data = await controller2.openVpn(req, res);
    if(data === 0) {
        return res.send(makeResponse(0, "", data));
    } else {
        if(data == -2) {
            return res.send(makeResponse(-2, "开启VPN失败，客户端秘钥不匹配，请重新生成并导入", data));
        } else if(data == -3) {
            return res.send(makeResponse(-2, "开启VPN失败，服务端秘钥不匹配，请重新生成并导入", data));
        }
        return res.send(makeResponse(data, "开启vpn失败", data));
    }
});

router.post('/close_vpn', async(req, res, next) => {
    let data = await controller2.closeVpn(req, res);
    if(data == 0) {
        return res.send(makeResponse(0, "", data));
    } else {
        return res.send(makeResponse(-1, "vpn关闭失败", data));
    }
});


module.exports = router;